package admin.controllers;

import helpers.ReadExcelHelper;
import helpers.StringHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import models.EmailModel;
import models.GeoModel;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.AsyncDatastoreService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import data.EmailData;

import admin.data.GeoData;

public class ImportEmailExcelServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		GeoData geoData = new GeoData();
		ArrayList<GeoModel> cities = geoData.getCities();
		
		String city = "";
		
		request.setAttribute("cities", cities);
		request.setAttribute("city", city);
		try {
			request.getRequestDispatcher("/admin/pages/import_email.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		HttpSession session = request.getSession();
		
		GeoData geoData = new GeoData();
		ArrayList<GeoModel> cities = geoData.getCities();
		
		String city = "";
		
		
		// Get the image representations
		try {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(500000);
	
			try {
				FileItemIterator iterator = upload.getItemIterator(request);
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream in = item.openStream();
					
					if (item.isFormField()) {
						if (item.getFieldName().equalsIgnoreCase("city")) {
							byte[] buffer = IOUtils.toByteArray(item.openStream());
							city = new String(buffer);
						}
					} else {
						List<String> lst = ReadExcelHelper.readColumnFromInputStream(in, 0);
						
						String txtEmail = "";
						
						AsyncDatastoreService ds = (AsyncDatastoreService) DatastoreServiceFactory.getAsyncDatastoreService();
						int count = 0;
						for (int i = 0 ; i < lst.size(); i++) {
							if (ValidateHelper.isEmail(lst.get(i))) {
								Key k = KeyFactory.createKey("EmailModel",lst.get(i));
								Entity entity = new Entity(k);
								
								entity.setProperty("city", city);
								entity.setProperty("status", 1);
								entity.setProperty("created", new Date());
								
								ds.put(entity);
								count ++;
							}
						}
						
						session.setAttribute("success", count + " email đã được lưu vào hệ thống... ");
					}
					
				}
			} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {
				session.setAttribute("error", "Dung lượng của file vượt quá giới hạn "
						+ e.getPermittedSize() + ". Dung lượng file là "
						+ e.getActualSize() + ".");
			}
		} catch (Exception ex) {
			//throw new ServletException(ex);
			//ex.printStackTrace();
			session.setAttribute("error", "Định dạng file bạn đưa lên không hợp lệ!");
		}
		
		
		request.setAttribute("cities", cities);
		request.setAttribute("city", city);
		try {
			request.getRequestDispatcher("/admin/pages/import_email.jsp").forward(request, response);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
}
